package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.redp.bizimpl.constant.UpmpConstant;
import cc.rengu.redp.bizimpl.enums.BizDataAuditStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizDataStatusEnum;
import cc.rengu.redp.bizimpl.enums.BizOprEnum;
import cc.rengu.redp.bizimpl.enums.PageOptFlagEnum;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.dao.AgentInfoMapper;
import cc.rengu.redp.bizimpl.upmp.domain.*;
import cc.rengu.redp.bizimpl.upmp.service.*;
import cc.rengu.redp.bizimpl.upmp.vo.OperationResult;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.DateUtils;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.DateUtil;
import cc.rengu.redp.common.utils.SortUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 刘玉亮.LL
 */
@Slf4j
@Service
public class AgentInfoServiceImpl extends ServiceImpl<AgentInfoMapper, AgentInfo> implements IAgentInfoService {


    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IUpmpOrganizationService organizationService;
    @Autowired
    private IBizTmpService bizTmpService;

    @Autowired
    private IBizHisService bizHisService;

    @Autowired
    private IFeeInfoService feeInfoService;

    @Autowired
    private IUpmpBPlatMchntInfoService platMchntInfoService;

    @Autowired
    private IProfitConfInfoService profitConfInfoService;
    @Autowired
    IUpmpPrivilegeCheckService privilegeCheckService;
    @Autowired
    private IUpmpSysSeqService upmpSysSeqService;

    private long oprMenuId = 20000019;
    private String oprMenuName = "商户管理:代理机构管理";
    private long chkMenuId = 20000019;
    private String chkMenuName = "商户管理:代理机构管理";
    private String webNextUrl = "/admin/merParam/agentInfo/edit";

    @Override
    public IPage<AgentInfo> findByPage(QueryRequest request, AgentInfo entity) {
        try {
            UpmpUserInfoVO user= CommonUtils.getCurrentUser(upmpSysParamService);
            LambdaQueryWrapper<AgentInfo> queryWrapper = new LambdaQueryWrapper<>();
            if (null != user && user.isAdmin()) {
                if(StringUtils.isNotBlank(entity.getInstId())){
                    queryWrapper.eq(AgentInfo::getInstId, entity.getInstId());
                }
            } else {
                //TODO 机构号查询条件暂时屏蔽
//            String crtOrgIds=user.getUserOrgCodes();
                String crtOrgIds="";
                queryWrapper.in(AgentInfo::getCrtOrgId,crtOrgIds);
            }
            if(Common.isNotBlank(entity.getAgentCode())){
                queryWrapper.likeRight(AgentInfo::getAgentCode,entity.getAgentCode());
            }
            if(Common.isNotBlank(entity.getAgentName())) {
                queryWrapper.likeRight(AgentInfo::getAgentName, entity.getAgentName());
            }
            if(Common.isNotBlank(entity.getManageInstId())) {
                queryWrapper.likeRight(AgentInfo::getManageInstId,entity.getManageInstId());
            }
            Page<AgentInfo> page = new Page<>();
            SortUtil.handlePageSort(request, page, "agentCode", UpmpConstant.ORDER_DESC, true);
            return this.page(page, queryWrapper);
        } catch (Exception e) {
            log.error("分页查询失败", e);
            return null;
        }
    }

    @Override
    public Map<String, Object>  orgExpandSelect2List(String q) {
        try {
            UpmpUserInfoVO user= CommonUtils.getCurrentUser(upmpSysParamService);
            LambdaQueryWrapper<AgentInfo> queryWrapper = new LambdaQueryWrapper<>();
            q = q.replaceAll("&amp;", "&");
            if (null == q) {
                return null;
            }

            String[] param = q.split("&");
            if (null != param && param.length > 0) {
                queryWrapper.or(qw -> qw.likeRight(AgentInfo::getAgentCode, param[0])
                        .likeRight(AgentInfo::getAgentName, param[0]));
            }
          queryWrapper.eq(AgentInfo::getAgentStatus,BusinessContainer.impStatus_01);
//          queryWrapper.in(AgentInfo::getCrtOrgId,GZIPUtils.uncompressToString(user.getUserOrgCodes()));
            List<AgentInfo> listx = this.list(queryWrapper);
            Map<String, Object> maps = new HashMap<String, Object>();
            Map<String, String> map = new HashMap<String, String>();
            List<Object> list = new ArrayList<Object>();
            for (int i = 0; i < listx.size(); i++) {
                AgentInfo ai = listx.get(i);
                map = new HashMap<String, String>();
                map.put("id", ai.getAgentCode().trim());
                map.put("name", ai.getAgentName().trim());
                list.add(map);
            }
            maps.put("results", list);
            maps.put("more", false);
            return maps;
        } catch (Exception e) {
            log.error("分页查询失败", e);
            return null;
        }
    }
    @Override
    public Map<String, Object> editShow(AgentInfo entity, String optFlag) throws RedpException {
        Map<String, Object> result = new HashMap<>();
        // 获取当前登录用户信息
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        LinkedHashMap<String, String> isMap = new LinkedHashMap<String, String>();
        isMap.put("1", "是");
        isMap.put("0", "否");
        optFlag = optFlag== null ? "" : optFlag;
        // 增加
        if ("add".equals(optFlag)) {
            String instId = entity.getInstId() == null ? "" : entity.getInstId();
            String crtOrgId = "";
            if(user.isAdmin()){
                if(StringUtils.isEmpty(instId)){
                    log.error("运营中心管理员新增数据必须先选择法人行！");
                    throw new RedpException("运营中心管理员新增数据必须先选择法人行！");
                }else{
                    UpmpOrganization headOrg=organizationService.getHeadOrgByCode(instId);
                    crtOrgId=(headOrg==null?user.getOrgCode():headOrg.getOrgCode());
                }
            }else{
                instId=(instId==null?user.getInstId():instId);
                crtOrgId=user.getOrgCode();
            }
            entity.setId("0");
            entity.setAgentCode("00000000");
            entity.setIsProfitFlag("0");
            entity.setIsShowAllFlag("0");
            entity.setAuditStatus(BusinessContainer.status_01);
            entity.setAgentStatus(BusinessContainer.agentStatus_00);

            UpmpOrganization org = organizationService.getOrgByCode(crtOrgId, instId);
            entity.setManageInstId(crtOrgId);
            entity.setInstId(instId);
            result.put("crtOrgName", org.getOrgName());
            result.put("manageInstName", org.getOrgName());
            result.put("profitConfInfoList", "[]");
        }
        // 修改，注销，停用，启用，详情，审批
        List<ProfitConfInfo> selectedProfitConfInfoList = new ArrayList<>();
        if (PageOptFlagEnum.OPT_FLAG_UPDATE.getType().equals(optFlag) || PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(optFlag) || PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(optFlag) ||
                PageOptFlagEnum.OPT_FLAG_USE.getType().equals(optFlag) || PageOptFlagEnum.OPT_FLAG_VIEW.getType().equals(optFlag) || PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
            String id = entity.getId();
            if (!"".equals(id)) {
                if (PageOptFlagEnum.OPT_FLAG_CHECK.getType().equals(optFlag)) {
                    BizTmp tmp = bizTmpService.getById(id);
                    if (Common.isBlank(tmp)) {
                        log.error("根据id没有找到指定临时表数据！");
                        throw new RedpException("根据id没有找到指定临时表数据！");
                    }
                    String bizdata = "";
                    if (null != tmp.getBizData1()) {
                        bizdata += tmp.getBizData1();
                    }
                    if (null != tmp.getBizData2()) {
                        bizdata += tmp.getBizData2();
                    }
                    if (null != tmp.getBizData3()) {
                        bizdata += tmp.getBizData3();
                    }
                    entity = JSON.parseObject(bizdata, AgentInfo.class);
                    // 加载分润配置信息
                    if ("1".equals(entity.getIsProfitFlag())) {
                        selectedProfitConfInfoList = bizTmpService.getBizTmpByInstIdAndMasterKeyAndEname(entity.getInstId(), ProfitConfInfo.class, entity.getId());
                    }
                    result.put("profitConfInfoList", JSON.toJSONString(selectedProfitConfInfoList));
                    // 处理修改前后数据
                    String auditStatus = tmp.getAuditStatus();
                    if (BusinessContainer.status_41.equals(auditStatus)) {
                        AgentInfo oldEntity = this.getById(id);
                        AgentInfo changeData = compEntity(entity, oldEntity);
                        //修改时对比详情数据
                        result.put("checkUpdate", "Y");
                        result.put("changeData", StringEscapeUtils.escapeHtml4(JSON.toJSONString(changeData, SerializerFeature.WriteMapNullValue)));

                    }
                } else {
                    entity = this.getById(id);
                    //分润数据 固定金额类型的 如果存在多条将合并显示
                    //设置结算周期
                    String settleType = entity.getSettleType();
                    if ("TN".equals(settleType)) {
                        entity.setSettleCycleType("1");
                    } else if ("MT".equals(settleType)) {
                        entity.setSettleCycleType("2");
                    } else if ("ST".equals(settleType)) {
                        entity.setSettleCycleType("3");
                    }
                    selectedProfitConfInfoList = profitConfInfoService.findByBizCode(entity.getAgentCode());
                    result.put("profitConfInfoList", JSON.toJSONString(selectedProfitConfInfoList));
                }

                UpmpOrganization organization = organizationService.getOrgByCode(entity.getCrtOrgId(), entity.getInstId());
                UpmpOrganization manageOrg = organizationService.getOrgByCode(entity.getManageInstId(), entity.getInstId());
                String crtOrgName = "";
                String manageInstName = "";
                if (organization != null) {
                    crtOrgName = organization.getOrgName();
                }
                if (manageOrg != null) {
                    manageInstName = manageOrg.getOrgName();
                }
                result.put("crtOrgName", crtOrgName);
                result.put("manageInstName", manageInstName);
            } else {
                log.error("请求参数(id)异常!");
                throw new RedpException("请求参数(id)异常！");
            }
        }

        // 1、生成所有基础产品的分润配置
        Map<BBaseProdInfo, List<ProfitConfInfo>> bBaseProdProfitConfListMap = platMchntInfoService.getProfitConfInfoList();
        // 将所有的产品分润配置，赋值已配置的分润配置id。用于前端反显
        Map<String, String> selectProfitConfInfoIdMap = new HashMap<>();
        for (ProfitConfInfo profitConfInfo : selectedProfitConfInfoList) {
            String sb = profitConfInfo.getBizProdCode() +
                    profitConfInfo.getSubProdType() +
                    (StringUtils.isNotBlank(profitConfInfo.getDstChannelType()) ? profitConfInfo.getDstChannelType() : "");
            //
            selectProfitConfInfoIdMap.put(sb, profitConfInfo.getId());
        }
        for (BBaseProdInfo bBaseProdInfo : bBaseProdProfitConfListMap.keySet()) {
            List<ProfitConfInfo> profitConfInfos = bBaseProdProfitConfListMap.get(bBaseProdInfo);
            for (ProfitConfInfo profitConfInfo : profitConfInfos) {
                String sb = profitConfInfo.getBizProdCode() +
                        profitConfInfo.getSubProdType() +
                        (StringUtils.isNotBlank(profitConfInfo.getDstChannelType()) ? profitConfInfo.getDstChannelType() : "");
                if (selectProfitConfInfoIdMap.containsKey(sb)) {
                    // 替换id
                    profitConfInfo.setId(selectProfitConfInfoIdMap.get(sb));
                }
            }
        }

        List<BBaseProdInfo> bBaseProdInfos = new ArrayList<>(bBaseProdProfitConfListMap.keySet());
        result.put("baseProdInfoList", JSON.toJSONString(bBaseProdInfos));

        List<ProfitConfInfo> profitConfInfos = new ArrayList<>();
        for (List<ProfitConfInfo> pc : bBaseProdProfitConfListMap.values()) {
            profitConfInfos.addAll(pc);
        }
        result.put("profitConfInfoAll", JSON.toJSONString(profitConfInfos));

        //
        result.put("optFlag", optFlag);
        result.put("entity", entity);
        result.put("isMap", isMap);

        result.put("manageInstId", entity.getManageInstId());
        result.put("auditStatus", entity.getAuditStatus());
        result.put("agentStatus", entity.getAgentStatus());
        result.put("crtOrgId", entity.getCrtOrgId());
        result.put("oprId", entity.getOprId());
        result.put("createTime", entity.getCreateTime());
        result.put("lastOprId", entity.getLastOprId());
        result.put("lastUpdateTime", entity.getLastUpdateTime());
        return result;
    }

    private AgentInfo compEntity(AgentInfo entity, AgentInfo oldEntity) throws RedpException {
        AgentInfo changeData = new AgentInfo();
        if (Common.isBlank(entity) || Common.isBlank(oldEntity)) {
            throw new RedpException("详情数据异常");
        }

        if (!(StringUtils.equals(entity.getAgentName(), oldEntity.getAgentName()))) {
            changeData.setAgentName(oldEntity.getAgentName());
        } else {
            changeData.setAgentName("unChange--data");//提示前端数据未改变
        }

        if (!(StringUtils.equals(entity.getAgentSimpleName(), oldEntity.getAgentSimpleName()))) {
            changeData.setAgentSimpleName(oldEntity.getAgentSimpleName());
        } else {
            changeData.setAgentSimpleName("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getSuperAgentCode(), oldEntity.getSuperAgentCode()))) {
            changeData.setSuperAgentCode(oldEntity.getSuperAgentCode());
        } else {
            changeData.setSuperAgentCode("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getManageInstId(), oldEntity.getManageInstId()))) {
            changeData.setManageInstId(oldEntity.getManageInstId());
        } else {
            changeData.setManageInstId("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getLicenceType(), oldEntity.getLicenceType()))) {
            changeData.setLicenceType(oldEntity.getLicenceType());
        } else {
            changeData.setLicenceType("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getLicenceCode(), oldEntity.getLicenceCode()))) {
            changeData.setLicenceCode(oldEntity.getLicenceCode());
        } else {
            changeData.setLicenceCode("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getArtifName(), oldEntity.getArtifName()))) {
            changeData.setArtifName(oldEntity.getArtifName());
        } else {
            changeData.setArtifName("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getArtifCertType(), oldEntity.getArtifCertType()))) {
            changeData.setArtifCertType(oldEntity.getArtifCertType());
        } else {
            changeData.setArtifCertType("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getArtifCertNo(), oldEntity.getArtifCertNo()))) {
            changeData.setArtifCertNo(oldEntity.getArtifCertNo());
        } else {
            changeData.setArtifCertNo("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getArtifMobile(), oldEntity.getArtifMobile()))) {
            changeData.setArtifMobile(oldEntity.getArtifMobile());
        } else {
            changeData.setArtifMobile("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getArtifEmail(), oldEntity.getArtifEmail()))) {
            changeData.setArtifEmail(oldEntity.getArtifEmail());
        } else {
            changeData.setArtifEmail("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getContactName(), oldEntity.getContactName()))) {
            changeData.setContactName(oldEntity.getContactName());
        } else {
            changeData.setContactName("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getContactPhone(), oldEntity.getContactPhone()))) {
            changeData.setContactPhone(oldEntity.getContactPhone());
        } else {
            changeData.setContactPhone("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getContactEmaiil(), oldEntity.getContactEmaiil()))) {
            changeData.setContactEmaiil(oldEntity.getContactEmaiil());
        } else {
            changeData.setContactEmaiil("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getPostCode(), oldEntity.getPostCode()))) {
            changeData.setPostCode(oldEntity.getPostCode());
        } else {
            changeData.setPostCode("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getAgentAddr(), oldEntity.getAgentAddr()))) {
            changeData.setAgentAddr(oldEntity.getAgentAddr());
        } else {
            changeData.setAgentAddr("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getIsProfitFlag(), oldEntity.getIsProfitFlag()))) {
            changeData.setAgentAddr(oldEntity.getAgentAddr());
        } else {
            changeData.setAgentAddr("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getIsProfitFlag(), oldEntity.getIsProfitFlag()))) {
            changeData.setIsProfitFlag(oldEntity.getIsProfitFlag());
        } else {
            changeData.setIsProfitFlag("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getIsShowAllFlag(), oldEntity.getIsShowAllFlag()))) {
            changeData.setIsShowAllFlag(oldEntity.getIsShowAllFlag());
        } else {
            changeData.setIsShowAllFlag("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getSettleType(), oldEntity.getSettleType()))) {
            changeData.setSettleType(oldEntity.getSettleType());
        } else {
            changeData.setSettleType("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getSettleType(), oldEntity.getSettleType())) || !(StringUtils.equals(entity.getSettleCycle() + "", oldEntity.getSettleCycle() + ""))) {
            changeData.setSettleType(oldEntity.getSettleType());
            changeData.setSettleCycle(oldEntity.getSettleCycle());
        } else {
            changeData.setSettleType("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getSettleAcctType(), oldEntity.getSettleAcctType()))) {
            changeData.setSettleAcctType(oldEntity.getSettleAcctType());
        } else {
            changeData.setSettleAcctType("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getSettleAcctNo(), oldEntity.getSettleAcctNo()))) {
            changeData.setSettleAcctNo(oldEntity.getSettleAcctNo());
        } else {
            changeData.setSettleAcctNo("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getSettleAcctName(), oldEntity.getSettleAcctName()))) {
            changeData.setSettleAcctName(oldEntity.getSettleAcctName());
        } else {
            changeData.setSettleAcctName("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getAcctOpenBankNo(), oldEntity.getAcctOpenBankNo()))) {
            changeData.setAcctOpenBankNo(oldEntity.getAcctOpenBankNo());
        } else {
            changeData.setAcctOpenBankNo("unChange--data");//提示前端数据未改变
        }
        if (!(StringUtils.equals(entity.getAcctOpenBankName(), oldEntity.getAcctOpenBankName()))) {
            changeData.setAcctOpenBankName(oldEntity.getAcctOpenBankName());
        } else {
            changeData.setAcctOpenBankName("unChange--data");//提示前端数据未改变
        }

        return changeData;
    }
    @Override
    @Transactional(value = "transactionManager")
    public OperationResult saveData(String menuId, String oprMenuName, AgentInfo entity,  HttpServletRequest request, String webNextUrl) throws RedpException {
        Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        String lastUpddt = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");
        UpmpUserInfoVO user =CommonUtils.getCurrentUser(upmpSysParamService);
        String instId = entity.getInstId();
        String crtOrgId = "";
        String optFlag = request.getParameter("optFlag") == null ? "" : request.getParameter("optFlag");
        if(optFlag.equals("add")&&user.isAdmin()){
            if(StringUtils.isEmpty(instId)){
                log.error("保存数据时请先选择法人行!");
                return OperationResult.buildFailureResult("保存数据时请先选择法人行!");
            }else{
                UpmpOrganization headOrg=organizationService.getHeadOrgByCode(instId);
                crtOrgId=(headOrg==null?user.getOrgCode():headOrg.getOrgCode());
            }
        }else{
            instId=(instId==null?user.getInstId():instId);
            crtOrgId=(entity.getCrtOrgId()==null?user.getOrgCode():entity.getCrtOrgId());
        }
        UpmpOrganization org = organizationService.getOrgByCode(crtOrgId, instId);

        entity.setLastOprId(user.getId());
        entity.setLastUpdateTime(lastUpddt);

        List<ProfitConfInfo> saveProfit;
        List<ProfitConfInfo> expProfit;

        AgentInfo oldEntity = null;
        if (!PageOptFlagEnum.OPT_FLAG_ADD.getType().equals(optFlag)) {
            oldEntity = this.getById(entity.getId());
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String nowDate = sdf.format(new Date());


        // “新增”或“修改”
        if (optFlag.equals("add") || optFlag.equals("upd")) {
            if (optFlag.equals("add")) {
                entity.setId(null);
                entity.setAgentCode(generateCode(instId));
                entity.setOprId(user.getId());
                entity.setInstId(instId);
                entity.setCrtOrgId(crtOrgId);
                entity.setCreateTime(lastUpddt);

                // 分润信息处理
                saveProfit = findProfitConfInfoList(entity);

                //获取审核信息
                UpmpPrivilegeCheck privilegeCheck = privilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "agentInfo:add");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    //需要审核
                    entity.setAuditStatus(BusinessContainer.status_01);
                    entity.setAgentStatus(BusinessContainer.agentStatus_00);
                    //保存entity profitconfList TMP
                    this.saveOrUpdate(entity);
                    entity.setProfitConfInfoList(null);
                    bizTmpService.saveBizTmpDtl(entity, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(), DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN),
                            menuId, oprMenuName, entity.getAgentStatus(), entity.getAuditStatus(), entity.getId(), webNextUrl, "N", "", null, null, null);

                    //直接保存新的分润信息
                    for (ProfitConfInfo profitConfInfo : saveProfit) {
                        profitConfInfo.setInstId(org.getInstId());
                        profitConfInfo.setProfitType("01");
                        profitConfInfo.setBizCode(entity.getAgentCode());
                        profitConfInfo.setProfitEffectiveDate(nowDate);
                        profitConfInfo.setProfitExpiryDate(BusinessContainer.doomsday);
                        profitConfInfo.setProfitStatus(entity.getAgentStatus());
                        profitConfInfo.setAuditStatus(entity.getAuditStatus());
                        profitConfInfo.setLastAuditId(user.getId());
                        profitConfInfo.setLastAuditTime(lastUpddt);
                        // 生成 分润配置唯一标识
                        profitConfInfo.setProfitPrimaryKey(platMchntInfoService.genProfitPrimaryKey(profitConfInfo));
                        // 分润配置信息保存正式表
                        profitConfInfoService.save(profitConfInfo);
                        // 分润配置明细保存临时表
                        bizTmpService.saveBizTmpDtl(profitConfInfo, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(),DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN),
                                menuId, oprMenuName, entity.getAgentStatus(), entity.getAuditStatus(), profitConfInfo.getId(), webNextUrl, "Y", entity.getId(), null, null, null);
                    }
                } else {
                    entity.setAuditStatus(BusinessContainer.status_02);
                    entity.setAgentStatus(BusinessContainer.agentStatus_01);
                    //保存 entity profitconfList His
                    this.saveOrUpdate(entity);
                    entity.setProfitConfInfoList(null);
                    bizHisService.saveBizHisNew(entity, entity, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(),DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN), menuId, oprMenuName, entity.getId(), null, null, null);

                    //直接保存新的分润信息
                    for (ProfitConfInfo profitConfInfo : saveProfit) {
                        profitConfInfo.setInstId(org.getInstId());
                        profitConfInfo.setProfitType("01");
                        profitConfInfo.setBizCode(entity.getAgentCode());
                        profitConfInfo.setProfitEffectiveDate(nowDate);
                        profitConfInfo.setProfitExpiryDate(BusinessContainer.doomsday);
                        profitConfInfo.setProfitStatus(entity.getAgentStatus());
                        profitConfInfo.setAuditStatus(entity.getAuditStatus());
                        profitConfInfo.setLastAuditId(user.getId());
                        profitConfInfo.setLastAuditTime(lastUpddt);
                        // 生成 分润配置唯一标识
                        profitConfInfo.setProfitPrimaryKey(platMchntInfoService.genProfitPrimaryKey(profitConfInfo));

                        // 分润配置信息保存正式表
                        profitConfInfoService.save(profitConfInfo);
                        // 分润配置明细保存历史表
                        bizHisService.saveBizHisNew(profitConfInfo, profitConfInfo, user, org.getInstId(), BizOprEnum.OPR_ADD.getType(),DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN), menuId, oprMenuName, profitConfInfo.getId(), null, null, null);
                    }
                }
            } else if (optFlag.equals("upd")) {
                AgentInfo dbAgentInfo = this.getById(entity.getId());
                //获取审核信息
                UpmpPrivilegeCheck privilegeCheck = privilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "agentInfo:update");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    // 1、修改的数据存入临时表，正式表仅修改状态
                    dbAgentInfo.setAuditStatus(BusinessContainer.status_41);
                    dbAgentInfo.setLastOprId(user.getId());
                    dbAgentInfo.setLastUpdateTime(lastUpddt);
                   this.saveOrUpdate(dbAgentInfo);

                    // 1.1、入临时表
                    entity.setAuditStatus(dbAgentInfo.getAuditStatus());
                    entity.setLastOprId(dbAgentInfo.getLastOprId());
                    entity.setLastUpdateTime(dbAgentInfo.getLastUpdateTime());
                    saveProfit = findProfitConfInfoList(entity);
                    entity.setProfitConfInfoList(null);
                    bizTmpService.saveBizTmpDtl(entity, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(),DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN),
                            menuId, oprMenuName, dbAgentInfo.getAgentStatus(), dbAgentInfo.getAuditStatus(), dbAgentInfo.getId(), webNextUrl, "N", "", null, null, null);

                    // 2、获取分润配置正式表数据，并且修改状态； 获取临时表分润配置信息，进行数据的修改
                    expProfit = profitConfInfoService.findByBizCode(entity.getAgentCode());
                    for (ProfitConfInfo profitConfInfo : expProfit) {
                        profitConfInfo.setAuditStatus(dbAgentInfo.getAuditStatus());
                        profitConfInfo.setLastOprId(user.getId());
                        profitConfInfo.setLastUpdateTime(lastUpddt);
                        profitConfInfoService.save(profitConfInfo);
                    }
                    List<BizTmp> bizTmpByMasterKey = bizTmpService.getBizTmpByMasterKey(entity.getInstId(), entity.getId());
                    List<BizTmp> deleteProfitConfBizTmps = new ArrayList<>();
                    for (BizTmp bizTmp : bizTmpByMasterKey) {
                        // 筛选分润配置信息
                        if ("t_b_profit_conf_info".equals(bizTmp.getOprTableEname().toLowerCase())) {
                            deleteProfitConfBizTmps.add(bizTmp);
                        }
                    }
                    // 2.1、先删除临时表 分润配置信息数据
                    bizTmpService.delete(deleteProfitConfBizTmps);
                    // 2.2、将修改后分润配置信息保存到临时表

                    for (ProfitConfInfo profitConfInfo : saveProfit) {
                        profitConfInfo.setId(CommonUtils.getUUID());
                        profitConfInfo.setInstId(dbAgentInfo.getInstId());
                        profitConfInfo.setProfitType("01");
                        profitConfInfo.setBizCode(dbAgentInfo.getAgentCode());
                        profitConfInfo.setProfitEffectiveDate(nowDate);
                        profitConfInfo.setProfitExpiryDate(BusinessContainer.doomsday);
                        profitConfInfo.setProfitStatus(dbAgentInfo.getAgentStatus());
                        profitConfInfo.setAuditStatus(dbAgentInfo.getAuditStatus());
                        profitConfInfo.setLastAuditId(user.getId());
                        profitConfInfo.setLastAuditTime(lastUpddt);
                        // 生成 分润配置唯一标识
                        profitConfInfo.setProfitPrimaryKey(platMchntInfoService.genProfitPrimaryKey(profitConfInfo));

                        bizTmpService.saveBizTmpDtl(profitConfInfo, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(),DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN),
                                menuId, oprMenuName, dbAgentInfo.getAgentStatus(), profitConfInfo.getAuditStatus(), profitConfInfo.getId(), webNextUrl, "Y", dbAgentInfo.getId(), null, null, null);
                    }
                } else {
                    //保存正式表 profitconfList His
                    entity.setAuditStatus(BusinessContainer.status_42);
                    entity.setAgentStatus(BusinessContainer.agentStatus_01);
                    saveProfit = findProfitConfInfoList(entity);
                    this.saveOrUpdate(entity);
                    entity.setProfitConfInfoList(null);
                    // 保存历史表
                    bizHisService.saveBizHisNew(entity, oldEntity, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(),DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN),
                            menuId, oprMenuName, entity.getId(), null, null, null);

                    // 处理旧分润信息
                    expProfit = profitConfInfoService.findByBizCode(entity.getAgentCode());
                    //原分润信息 全部设置为到期
                    for (ProfitConfInfo p : expProfit) {
                        profitConfInfoService.cancle(p);
                    }

                    //分润信息处理


                    //保存新的分润信息
                    for (ProfitConfInfo p : saveProfit) {
                        p.setInstId(org.getInstId());
                        p.setProfitType("01");
                        p.setBizCode(entity.getAgentCode());
                        p.setProfitEffectiveDate(nowDate);
                        p.setProfitExpiryDate(BusinessContainer.doomsday);
                        p.setProfitStatus(entity.getAgentStatus());
                        p.setAuditStatus(entity.getAuditStatus());
                        p.setLastAuditId(user.getId());
                        p.setLastAuditTime(lastUpddt);
                        // 生成 分润配置唯一标识
                        p.setProfitPrimaryKey(platMchntInfoService.genProfitPrimaryKey(p));
                        profitConfInfoService.save(p);

                        bizHisService.saveBizHisNew(p, p, user, org.getInstId(), BizOprEnum.OPR_UPDATE.getType(),DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN),
                                menuId, oprMenuName, p.getId(), null, null, null);
                    }
                }
            }

        }
        // 停用，启用，注销
        if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(optFlag)
                || PageOptFlagEnum.OPT_FLAG_USE.getType().equals(optFlag)
                || PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(optFlag)) {
            String id = entity.getId();
            if (Common.isBlank(id)) {
                log.error("请求参数(id)异常!");
                return OperationResult.buildFailureResult("请求参数(id)异常!", result);
            }
            AgentInfo dbAgentInfo = this.getById(id);
            if (Common.isBlank(dbAgentInfo)) {
                log.error("根据id没有找到指定数据！");
                return OperationResult.buildFailureResult("根据id没有找到指定数据！", result);
            }

            AgentInfo agentInfo = new AgentInfo();
            BeanUtils.copyProperties(dbAgentInfo, agentInfo);

            UpmpPrivilegeCheck privilegeCheck = new UpmpPrivilegeCheck();
            String bizOpr = "";
            String stopReason = "";
            String cancelReason = "";
            if (PageOptFlagEnum.OPT_FLAG_STOP.getType().equals(optFlag)) {
                stopReason = request.getParameter("stopReason");
                bizOpr = BizOprEnum.OPR_STOP.getType();
                privilegeCheck = privilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "agentInfo:stop");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    agentInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType());
                } else {
                    agentInfo.setStopReason(stopReason);
                    agentInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                    agentInfo.setAgentStatus(BizDataStatusEnum.STATUS_STOPED.getType());
                }
            } else if (PageOptFlagEnum.OPT_FLAG_USE.getType().equals(optFlag)) {

                bizOpr = BizOprEnum.OPR_USE.getType();
                privilegeCheck = privilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "agentInfo:use");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    agentInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType());
                } else {
                    agentInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                    agentInfo.setAgentStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
                }
            } else if (PageOptFlagEnum.OPT_FLAG_CANCEL.getType().equals(optFlag)) {
                cancelReason = request.getParameter("cancelReason");
                bizOpr = BizOprEnum.OPR_CANCEL.getType();
                privilegeCheck = privilegeCheckService.getPrivilegeCheckByPrivilegeCode(user.getInstId(), "agentInfo:cancel");
                if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                    agentInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType());
                } else {
                    agentInfo.setCancelReason(cancelReason);
                    agentInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                    agentInfo.setAgentStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
                }
            }
            agentInfo.setLastOprId(user.getId());
            agentInfo.setLastUpdateTime(lastUpddt);

            this.saveOrUpdate(agentInfo);
            agentInfo.setProfitConfInfoList(null);
            if (null != privilegeCheck && BusinessContainer.YES.equals(privilegeCheck.getChecked())) {
                //检查临时表是否有数据，如果没用则新增
                if(Common.isNotBlank(stopReason)){
                    agentInfo.setStopReason(stopReason);
                }
                if(Common.isNotBlank(cancelReason)){
                    agentInfo.setCancelReason(cancelReason);
                }
                bizTmpService.saveBizTmpDtl(agentInfo, user, org.getInstId(), bizOpr,DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN)
                        , menuId, oprMenuName, agentInfo.getAgentStatus(), agentInfo.getAuditStatus(), agentInfo.getId(), webNextUrl, "N", "", null, null, null);
            } else {
                //历史表新增
                bizHisService.saveBizHisNew(agentInfo, dbAgentInfo, user, org.getInstId(), bizOpr,DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN)
                        , menuId, oprMenuName, agentInfo.getId(), null, null, null);
            }
            result.put("id", agentInfo.getId());
            return OperationResult.buildSuccessResult("数据保存处理完成", result);
        }

        result.put("id", entity.getId());
        return OperationResult.buildSuccessResult("数据保存处理完成", result);
    }

    private List<ProfitConfInfo> findProfitConfInfoList(AgentInfo agentInfo) throws RedpException {
        List<ProfitConfInfo> list = new ArrayList<>();

        // 不参与分润
        if (agentInfo.getIsProfitFlag().equals("0")) {
            return list;
        }

        // 全产品分润 保存时是将每个基础产品的分润都配置成这种分润规则
        if (agentInfo.getProfitRule().equals("00")) {
            // 获取全部产品分润配置
            Map<BBaseProdInfo, List<ProfitConfInfo>> profitConfInfoListMap = platMchntInfoService.getProfitConfInfoList();
            List<ProfitConfInfo> profitConfInfos = new ArrayList<>();
            for (List<ProfitConfInfo> pc : profitConfInfoListMap.values()) {
                profitConfInfos.addAll(pc);
            }
            //
            for (ProfitConfInfo profitConfInfo : profitConfInfos) {
                // 如果固定金额
                if (agentInfo.getProfitInputModeALL().equals("01")) {
                    //固定金额费率模板不为空；加载费率模板数据进行填充
                    if(StringUtils.isNotBlank(agentInfo.getProfitFixedIndexALL())){
                        //查询费率模板，是否存在多条费率，如果是保存多条
                        List<FeeInfo> feeInfos = feeInfoService.findallBypCalType(agentInfo.getProfitFixedIndexALL(), agentInfo.getInstId());
                        for (FeeInfo feeInfo : feeInfos) {
                            ProfitConfInfo profitConfInfoTarget = new ProfitConfInfo();
                            BeanUtils.copyProperties(profitConfInfo, profitConfInfoTarget);

                            profitConfInfoTarget.setProfitInputMode(agentInfo.getProfitInputModeALL());

                            profitConfInfoTarget.setProfitFixedIndex(feeInfo.getPSeqNo());
                            profitConfInfoTarget.setProfitFixedStart(Common.isBlank(feeInfo.getPStartValue())?"":feeInfo.getPStartValue().toString());
                            profitConfInfoTarget.setProfitFixedEnd(Common.isBlank(feeInfo.getPEndValue())?"":feeInfo.getPEndValue().toString());
                            profitConfInfoTarget.setProfitFixedAmt(Common.isBlank(feeInfo.getPValue())?"":feeInfo.getPValue().toString());

                            profitConfInfoTarget.setProfitScale(agentInfo.getProfitScaleALL());
                            profitConfInfoTarget.setProfitCappingAmt(agentInfo.getProfitCappingAmtALL());

                            profitConfInfoTarget.setCostCappingAmt(agentInfo.getCostCappingAmtALL());
                            profitConfInfoTarget.setCostFeeRate(agentInfo.getCostFeeRateALL());

                            profitConfInfoTarget.setRemark1(feeInfo.getFeeCd() + "," + feeInfo.getFeeName());
                            list.add(profitConfInfoTarget);
                        }
                    }else{
                        ProfitConfInfo profitConfInfoTarget = new ProfitConfInfo();
                        BeanUtils.copyProperties(profitConfInfo, profitConfInfoTarget);

                        profitConfInfoTarget.setProfitInputMode(agentInfo.getProfitInputModeALL());

                        profitConfInfoTarget.setProfitFixedIndex(0);
                        profitConfInfoTarget.setProfitFixedStart("0");
                        profitConfInfoTarget.setProfitFixedEnd("99999999999999.99");
                        profitConfInfoTarget.setProfitFixedAmt(agentInfo.getProfitFixedAmtALL());

                        profitConfInfoTarget.setProfitScale(agentInfo.getProfitScaleALL());
                        profitConfInfoTarget.setProfitCappingAmt(agentInfo.getProfitCappingAmtALL());

                        profitConfInfoTarget.setCostCappingAmt(agentInfo.getCostCappingAmtALL());
                        profitConfInfoTarget.setCostFeeRate(agentInfo.getCostFeeRateALL());

                        list.add(profitConfInfoTarget);
                    }
                } else {
                    profitConfInfo.setProfitFixedIndex(0);

                    profitConfInfo.setProfitInputMode(agentInfo.getProfitInputModeALL());
                    profitConfInfo.setProfitFixedAmt(agentInfo.getProfitFixedAmtALL());
                    profitConfInfo.setProfitScale(agentInfo.getProfitScaleALL());
                    profitConfInfo.setProfitCappingAmt(agentInfo.getProfitCappingAmtALL());
                    profitConfInfo.setCostCappingAmt(agentInfo.getCostCappingAmtALL());
                    profitConfInfo.setCostFeeRate(agentInfo.getCostFeeRateALL());

                    list.add(profitConfInfo);
                }
            }
            // 全产品统一分润只在新增时显示
            agentInfo.setProfitRule("01");
        } else if (agentInfo.getProfitRule().equals("01")) {
            //业务产品分润
            List<ProfitConfInfo> profitConfInfos = JSON.parseArray(agentInfo.getProfitConfInfoList(), ProfitConfInfo.class);

            for (ProfitConfInfo profitConfInfo : profitConfInfos) {
                //如果固定金额
                if (profitConfInfo.getProfitInputMode().equals("01")) {
                    //固定金额费率模板不为空
                    if(StringUtils.isNotBlank(profitConfInfo.getProfitFixedIndexS())){
                        //查询费率模板，是否存在多条费率，如果是保存多条
                        List<FeeInfo> feeInfos = feeInfoService.findallBypCalType(profitConfInfo.getProfitFixedIndexS(), agentInfo.getInstId());
                        for (FeeInfo f : feeInfos) {
                            ProfitConfInfo ALL = new ProfitConfInfo();

                            ALL.setProfitInputMode(profitConfInfo.getProfitInputMode());

                            ALL.setProfitFixedIndex(f.getPSeqNo());
                            ALL.setProfitFixedStart(Common.isBlank(f.getPStartValue())?"":f.getPStartValue().toString());
                            ALL.setProfitFixedEnd(Common.isBlank(f.getPEndValue())?"":f.getPEndValue().toString());
                            ALL.setProfitFixedAmt(Common.isBlank(f.getPValue())?"":f.getPValue().toString());


                            ALL.setDstChannelType(profitConfInfo.getDstChannelType());
                            ALL.setBizProdCode(profitConfInfo.getBizProdCode());
                            ALL.setSubProdType(profitConfInfo.getSubProdType());
                            ALL.setRemark1(f.getFeeCd() + "," + f.getFeeName());
                            list.add(ALL);
                        }
                    }else{
                        ProfitConfInfo ALL = new ProfitConfInfo();
                        ALL.setProfitInputMode(profitConfInfo.getProfitInputMode());
                        ALL.setProfitFixedIndex(0);
                        ALL.setProfitFixedStart("0");
                        ALL.setProfitFixedEnd("99999999999999.99");
                        ALL.setProfitFixedAmt(profitConfInfo.getProfitFixedAmt());

                        ALL.setDstChannelType(profitConfInfo.getDstChannelType());
                        ALL.setBizProdCode(profitConfInfo.getBizProdCode());
                        ALL.setSubProdType(profitConfInfo.getSubProdType());
                        list.add(ALL);
                    }
                } else {
                    ProfitConfInfo ALL = new ProfitConfInfo();

                    ALL.setProfitFixedIndex(0);

                    ALL.setProfitInputMode(profitConfInfo.getProfitInputMode());
                    ALL.setProfitFixedAmt(profitConfInfo.getProfitFixedAmt());
                    ALL.setProfitScale(profitConfInfo.getProfitScale());
                    ALL.setProfitCappingAmt(profitConfInfo.getProfitCappingAmt());
                    ALL.setCostCappingAmt(profitConfInfo.getCostCappingAmt());
                    ALL.setCostFeeRate(profitConfInfo.getCostFeeRate());

                    ALL.setDstChannelType(profitConfInfo.getDstChannelType());
                    ALL.setBizProdCode(profitConfInfo.getBizProdCode());
                    ALL.setSubProdType(profitConfInfo.getSubProdType());
                    list.add(ALL);
                }
            }
        }
        return list;
    }

    @Override
    @Transactional(value = "transactionManager")
    public OperationResult chkData(String menuId, String oprMenuName, AgentInfo entity, HttpServletRequest request, String webNextUrl) throws RedpException {
        Map<String, Object> result = com.google.common.collect.Maps.newHashMap();
        String id = entity.getId();
        if (Common.isBlank(id)) {
            log.error("请求参数(id)异常!");
            return OperationResult.buildFailureResult("请求参数(id)异常!", result);
        }
        String opt = request.getParameter("optFlag");
        if (Common.isBlank(opt)) {
            log.error("请求参数(opt)异常!");
            return OperationResult.buildFailureResult("请求参数(opt)异常!", result);
        }

        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        SimpleDateFormat fmtdt = new SimpleDateFormat("yyyyMMddHHmmss");
        String lastUpddt = fmtdt.format(new Date());
        entity.setLastOprId(user.getId());
        entity.setLastUpdateTime(lastUpddt);

        // 1、组装代理机构实体类对象
        // 1.1、获取临时表代理机构的数据并转换成实体对象
        BizTmp tmp = bizTmpService.getById(id);
        if (Common.isBlank(tmp)) {
            log.error("根据id没有找到指定临时表数据！");
            return OperationResult.buildFailureResult("根据id没有找到指定临时表数据！", result);
        }
        String bizdata = "";
        if (null != tmp.getBizData1()) {
            bizdata += tmp.getBizData1();
        }
        if (null != tmp.getBizData2()) {
            bizdata += tmp.getBizData2();
        }
        if (null != tmp.getBizData3()) {
            bizdata += tmp.getBizData3();
        }
        // 1.2、代理机构临时表数据
        AgentInfo agentInfoNew = JSON.parseObject(bizdata, AgentInfo.class);
        // 1.3、代理机构正式表数据
        AgentInfo agentInfo = this.getById(id);
        // 1.3、备份代理机构正式表数据
        AgentInfo agentInfoOld = new AgentInfo();
        BeanUtils.copyProperties(agentInfo, agentInfoOld);

        if (Common.isBlank(agentInfo) && !BizOprEnum.OPR_ADD.equals(tmp.getBizOpr())) {
            log.error("根据id没有找到指定数据！");
            return OperationResult.buildFailureResult("根据id没有找到指定数据！", result);
        }
        // 2、组装分润配置实体类对象
        List<ProfitConfInfo> profitConfInfos = profitConfInfoService.findByBizCode(entity.getAgentCode());
        // 2.1、分润配置临时表数据
        List<ProfitConfInfo> profitConfInfosNew = bizTmpService.getBizTmpByInstIdAndMasterKeyAndEname(agentInfo.getInstId(), ProfitConfInfo.class, agentInfo.getId());
        // 2.2、备份分润配置正式表数据
        List<String> profitConfInfosOld = new ArrayList<>();
        for (ProfitConfInfo profitConfInfo : profitConfInfos) {
            ProfitConfInfo profitConfInfoOld = new ProfitConfInfo();
            BeanUtils.copyProperties(profitConfInfo, profitConfInfoOld);
            profitConfInfosOld.add(profitConfInfoOld.getId());
        }

        //
        if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
            // 审批通过将临时表数据更新到正式表
            BeanUtils.copyProperties(agentInfoNew, agentInfo);
            // 分润配置处理
            profitConfInfos.clear();
            for (ProfitConfInfo profitConfInfoNew : profitConfInfosNew) {
                ProfitConfInfo profitConfInfo = new ProfitConfInfo();
                BeanUtils.copyProperties(profitConfInfoNew, profitConfInfo);
                profitConfInfos.add(profitConfInfo);
            }
        } else {
            String auditRefuseReason = request.getParameter("auditRefuseReason");
            agentInfo.setAuditRefuseReason(auditRefuseReason);
        }

        String bizOpr = "";
        if (BizDataAuditStatusEnum.AUDIT_STATUS_ADD_CHECKING.getType().equals(agentInfo.getAuditStatus())) {
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                agentInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_PASS.getType());
                agentInfo.setAgentStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            } else {
                agentInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_ADD_REJECT.getType());
            }
            bizOpr = BizOprEnum.OPR_ADD.getType();
        } else if (BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_CHECKING.getType().equals(agentInfo.getAuditStatus())) {
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                agentInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_PASS.getType());
                agentInfo.setAgentStatus(BizDataStatusEnum.STATUS_CANCELED.getType());
            } else {
                agentInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_CANCEL_REJECT.getType());
            }
            bizOpr = BizOprEnum.OPR_CANCEL.getType();
        } else if (BizDataAuditStatusEnum.AUDIT_STATUS_STOP_CHECKING.getType().equals(agentInfo.getAuditStatus())) {
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                agentInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_PASS.getType());
                agentInfo.setAgentStatus(BizDataStatusEnum.STATUS_STOPED.getType());
            } else {
                agentInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_STOP_REJECT.getType());
            }
            bizOpr = BizOprEnum.OPR_STOP.getType();
        } else if (BizDataAuditStatusEnum.AUDIT_STATUS_USE_CHECKING.getType().equals(agentInfo.getAuditStatus())) {
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                agentInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_PASS.getType());
                agentInfo.setAgentStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            } else {
                agentInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_USE_REJECT.getType());
            }
            bizOpr = BizOprEnum.OPR_USE.getType();
        } else if (BizDataAuditStatusEnum.AUDIT_STATUS_UPD_CHECKING.getType().equals(agentInfo.getAuditStatus())) {
            if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
                agentInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_PASS.getType());
                agentInfo.setAgentStatus(BizDataStatusEnum.STATUS_NORMAL.getType());
            } else {
                agentInfo.setAuditStatus(BizDataAuditStatusEnum.AUDIT_STATUS_UPD_REJECT.getType());
            }
            bizOpr = BizOprEnum.OPR_UPDATE.getType();
        }

        // 状态赋值完成后，入库正式表
        this.saveOrUpdate(agentInfo);
        // 分润配置处理
        if (profitConfInfosOld.size() > 0 && !PageOptFlagEnum.OPT_FLAG_REJECT.getType().equals(opt)) {
            // 正式表先删除
            profitConfInfoService.delete(profitConfInfosOld);
        }
        for (ProfitConfInfo profitConfInfo : profitConfInfos) {
            profitConfInfo.setProfitStatus(agentInfo.getAgentStatus());
            profitConfInfo.setAuditStatus(agentInfo.getAuditStatus());
            profitConfInfoService.save(profitConfInfo);
        }
        //
        if (PageOptFlagEnum.OPT_FLAG_PASS.getType().equals(opt)) {
            //审批通过将正式表更新到历史表
            bizHisService.saveBizHisNew(agentInfo, agentInfoOld, user, user.getInstId(), bizOpr,DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN), menuId, oprMenuName, agentInfo.getId(), null, null, null);
            // 分润配置处理;无法与old对象对比
            for (ProfitConfInfo profitConfInfo : profitConfInfos) {
                bizHisService.saveBizHisNew(profitConfInfo, profitConfInfo, user, user.getInstId(), bizOpr,DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN), menuId, oprMenuName, profitConfInfo.getId(), null, null, null);
            }
        } else if (PageOptFlagEnum.OPT_FLAG_REJECT.getType().equals(opt)) {
            // 处理审核退回,profitConfInfosNew和profitConfInfos对象不一致数据的删除
            Map<String, Boolean> profiltConfInfoMap = new HashMap<>();
            for (ProfitConfInfo profitConfInfo : profitConfInfos) {
                profiltConfInfoMap.put(profitConfInfo.getId(), true);
            }
            for (ProfitConfInfo profitConfInfo : profitConfInfosNew) {
                if (!profiltConfInfoMap.containsKey(profitConfInfo.getId())) {
                    BizTmp bizTmp = bizTmpService.getById(profitConfInfo.getId());
                    if (null != bizTmp) {
                        bizTmpService.delete(bizTmp.getRealId());
                    }
                }
            }
        }
        // 修改临时表的审核状态等字段
        bizTmpService.saveBizTmpDtl(agentInfo, user, user.getInstId(), bizOpr,DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN), menuId, oprMenuName, agentInfo.getAgentStatus(), agentInfo.getAuditStatus(), agentInfo.getId(), webNextUrl, "N", "", null, null, null);
        // 分润配置处理
        for (ProfitConfInfo profitConfInfo : profitConfInfos) {
            bizTmpService.saveBizTmpDtl(profitConfInfo, user, user.getInstId(), bizOpr,DateUtil.getDateFormat(new Date(), DateUtil.FULL_TIME_WITH_MILL_SPLIT_PATTERN), menuId, oprMenuName, agentInfo.getAgentStatus(), profitConfInfo.getAuditStatus(), profitConfInfo.getId(), webNextUrl, "Y", agentInfo.getId(), null, null, null);
        }

        result.put("id", agentInfo.getId());
        return OperationResult.buildSuccessResult("数据保存处理完成", result);
    }
    /**
     * 系统自动生成代理商编码：AG + 8位顺序编码
     *
     * @return
     */
    public String generateCode(String instId) {
        // 获取渠道ID：固定20
        String channelId = CommonUtils.getChannelId(upmpSysParamService,instId);
        // 代理商编码前缀：AG
        String prefix = BusinessContainer.AgentCd_PREFIX;
        // 自动生成一级代码
        String paramCode = BusinessContainer.COMM_PARAM_CODE;
        // 生成序列号
        String seqNum =  upmpSysSeqService.updateParamValue(paramCode, "AGENT_CD", channelId);

        // 代理商编码
        String result = prefix + String.format("%08d", Integer.parseInt(seqNum));
        return result;
    }
    @Override
    @Transactional
    public void delete(String[] ids) {
        List<String> list = Arrays.asList(ids);
        this.baseMapper.deleteBatchIds(list);
    }
    @Override
    public Map<String, Object> agentCdSelect2List(QueryRequest request, String q) {
        UpmpUserInfoVO user = CommonUtils.getCurrentUser(upmpSysParamService);
        //q的格式为  EQ_instId & CN_feeCd_OR_feeName & EQ_pCalType
        q = q.replaceAll("&amp;", "&");
        if (null == q) {
            return null;
        }
        LambdaQueryWrapper<AgentInfo> wrapper = new LambdaQueryWrapper<>();
        String[] param = q.split("&");
        if (null != param && param.length > 0) {
            wrapper.or(wp -> {
                wp.likeRight(AgentInfo::getAgentCode, param[0])
                        .likeRight(AgentInfo::getAgentName, param[0]);
            });
        }
        String instId = "";
        if (null != param && param.length > 1) {
            instId = param[1];
        }
        wrapper.eq(AgentInfo::getAgentStatus, BusinessContainer.impStatus_01);
        if (null != user && user.isAdmin()) {
            wrapper.eq(AgentInfo::getInstId, instId);
        } else {
            //       wrapper.in(AgentInfo::getCrtOrgId,)GZIPUtils.uncompressToString(user.getUserOrgCodes());
        }
        Page<AgentInfo> page = new Page<>();
        SortUtil.handlePageSort(request, page, true);
        Page<AgentInfo> page1 = this.page(page, wrapper);
        Map<String, Object> maps = new HashMap<String, Object>();
        List<AgentInfo> listx = page1.getRecords();
        List<Object> list = new ArrayList<Object>();
        if (listx != null) {
            for (int i = 0; i < listx.size(); i++) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("id", listx.get(i).getAgentCode());
                map.put("name", listx.get(i).getAgentName());
                list.add(map);
            }
        }
        maps.put("results", list);
        int pageIndex = Common.isBlank(request.getPageNum()) ? 1 : request.getPageNum();
        if (pageIndex == page1.getTotal()) {
            maps.put("more", false);
        } else {
            maps.put("more", true);
        }
        return maps;
    }

    @Override
    public AgentInfo findOneByAgentCode(String agentCode, String instId){
        LambdaQueryWrapper<AgentInfo> wrapper= new LambdaQueryWrapper<>();
        wrapper.eq(AgentInfo::getAgentCode,agentCode);
        wrapper.eq(AgentInfo::getInstId,instId);
        return this.getOne(wrapper);

    }

    @Override
    public AgentInfo findOneByCode(String agentMchntNo, String status,String instId) {
        LambdaQueryWrapper<AgentInfo> wrapper= new LambdaQueryWrapper<>();
        wrapper.eq(AgentInfo::getAgentCode,agentMchntNo);
        wrapper.eq(AgentInfo::getAgentStatus,status);
        wrapper.eq(AgentInfo::getInstId,instId);
        return this.getOne(wrapper);
    }

    @Override
    public AgentInfo findOneByCodeAndCrtOrg(String agentMchntNo, String status, List<String> orgList) {
        LambdaQueryWrapper<AgentInfo> wrapper= new LambdaQueryWrapper<>();
        wrapper.eq(AgentInfo::getAgentCode,agentMchntNo);
        wrapper.eq(AgentInfo::getAgentStatus,status);
        wrapper.in(AgentInfo::getCrtOrgId,orgList);
        return this.getOne(wrapper);
    }
}
